package cn.sc.hunter.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 类操作工具
 */
public final class ClassUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClassUtil.class);
    private static final String PROTOCOL_FILE       = "file";
    private static final String PROTOCOL_JAR        = "jar";
    private static final String SUFFIX_CLASS        = ".class";

    /**
     * 获取类加载器
     */
    public static ClassLoader getClassLoader() {
        return  Thread.currentThread().getContextClassLoader();
    }
    /**
     * 加载类
     */
    public static Class<?> loadClass(String className) {
        Class<?> clazz = null;
        try {
            Class.forName(className, false, getClassLoader());
        } catch (ClassNotFoundException e) {
            LOGGER.error("类加载失败！");
            throw new RuntimeException(e);
        }
        return clazz;
    }

    /**
     * 加载类
     */
    public static Class<?> loadClass(String className, boolean initialize) {
        Class<?> clazz = null;
        try {
            Class.forName(className, initialize, getClassLoader());
        } catch (ClassNotFoundException e) {
            LOGGER.error("类加载失败！");
            throw new RuntimeException(e);
        }
        return clazz;
    }

    /**
     * 获取指定包下的所有类
     */
    public static Set<Class<?>> getClassSet(String packageName) {
        Set<Class<?>> set = new HashSet<>();
        try {
            Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".","/"));
            while (urls.hasMoreElements()){
                URL url = urls.nextElement();
                if (url != null) {
                    String protocol = url.getProtocol();
                    if (PROTOCOL_FILE.equals(protocol)) {
                        String packagePath = url.getPath().replaceAll("%20","");
                        addClass(set, packagePath, packageName);
                    } else if (PROTOCOL_JAR.equals(protocol)) {
                        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                        if (jarURLConnection != null) {
                            JarFile jarFile = jarURLConnection.getJarFile();
                            if (jarFile != null) {
                                Enumeration<JarEntry> entities = jarFile.entries();
                                while (entities.hasMoreElements()) {
                                    JarEntry entry = entities.nextElement();
                                    String entryName = entry.getName();
                                    if (entryName.endsWith(SUFFIX_CLASS)) {
                                        String className = entryName.substring(0, entryName.lastIndexOf(".")).replaceAll("/",".");
                                        set.add(loadClass(className, false));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {

        }
        return set;
    }

    /**
     * Class 添加到集合中
     */
    private static void addClass(Set<Class<?>> set, String packagePath, String packageName) {
        File[] files = new File(packageName).listFiles((f) -> {
            return (f.isFile() && f.getName().endsWith(SUFFIX_CLASS)) || f.isDirectory();
        });
        for (File file : files) {
            String fileName = file.getName();
            if (file.isFile()) {
                String className = fileName.substring(0, fileName.lastIndexOf("."));
                if (StringUtil.isNotEmpty(packageName)) {
                    className = packageName + "." + className;
                }
                set.add(loadClass(className, false));
            } else {
                String subPackagePath = fileName;
                if (StringUtil.isNotEmpty(packagePath)) {
                    subPackagePath = packagePath + "/" + subPackagePath;
                }
                String subPackageName = fileName;
                if (StringUtil.isNotEmpty(packageName)) {
                    subPackageName = packageName + "." + subPackageName;
                }
                addClass(set, subPackagePath, subPackageName);
            }
        }
    }
}
